import { BaseSys } from "../../BaseSys";
import { DComponents } from "./DComponents";

export class ComponentsMgr extends BaseSys {
    //依据id可获得的组件的集合
    private _entitys: { [key: number]: DComponents[] } = {}
    public static ins(): ComponentsMgr {
        return super.ins()
    }
    //加入组件
    public addComponent(id: number, component: DComponents) {
        if (!this._entitys[id]) {
            this._entitys[id] = []
        }
        let index = this._entitys[id].indexOf(component);
        if (index >= 0) {
            console.log(`${component}已在实体${id}中注册了`)
        } else {
            this._entitys[id].push(component);
        }
    }
    //使组件生效
    public enableComponent(id: number, component: DComponents) {
        this.setEnable(id, component, true)
    }
    //是组件不生效
    public disableComponent(id: number, component: DComponents) {
        this.setEnable(id, component, false)
    }
    private setEnable(id: number, component: DComponents, enale: boolean) {
        if (!this._entitys[id]) {
            console.log(`实体${id}没有发现组件`)
            return;
        }
        let components: DComponents[] = this._entitys[id]
        let index = components.indexOf(component)
        if (index >= 0) {
            if (component.enabled != enale) {
                component.enabled = enale;
            }
        } else {
            console.log(`${component}没有添加到实体${id}`)
        }
    }
    //移除组件
    public removeComponent(id: number, component: DComponents) {
        if (!this._entitys[id]) {
            console.log(`实体${id}没有发现组件`)
            return;
        }
        let components: DComponents[] = this._entitys[id]
        let index = components.indexOf(component)
        if (index >= 0) {
            components.splice(index, 1)
        } else {
            console.log(`${component}没有添加到实体${id}`)
        }
    }

    //移除所有组件
    public removeComponents(id: number) {
        delete this._entitys[id]
    }

    //获取当前的实体
    public getEntitys() {
        let entitys = []
        for (let id in this._entitys) {
            entitys.push(parseInt(id));
        }
        return entitys;
    }
    
    public getEntityById(id){
        return this._entitys[id];
    }

}